package com.miracle9.game.util;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

public class ClientIpProcess
{
  private static final Logger logger = Logger.getLogger(ClientIpProcess.class);
  private static Map<String, Integer> bP = new ConcurrentHashMap();
  private static ClientIpProcess bQ = null;
  
  public static ClientIpProcess startMethod()
  {
    if (bQ == null) {
      bQ = new ClientIpProcess();
    }
    return bQ;
  }
  
  public void clientIPSession(IoSession session)
  {
    String clientIP = ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();
    session.setAttribute("clientIP", clientIP);
  }
  
  public boolean blackIpSession(IoSession session)
  {
    String clientIP = (String)session.getAttribute("clientIP");
    logger.info("checkBlackList:" + clientIP);
    if ((bP.get(clientIP) != null) && 
      (((Integer)bP.get(clientIP)).intValue() > 30))
    {
      logger.error("black ip session:" + clientIP);
      return true;
    }
    return false;
  }
  
  public boolean unlockIpSession(IoSession session)
  {
    String clientIP = (String)session.getAttribute("clientIP");
    logger.info("dealUnLockBlackList checkBlackList:" + clientIP);
    if (bP.get(clientIP) != null)
    {
      logger.error("unlock black ip session:" + clientIP);
      bP.remove(clientIP);
      return true;
    }
    return false;
  }
  
  public void dealLoginError(IoSession session)
  {
    String clientIP = (String)session.getAttribute("clientIP");
    logger.info("dealLoginError:" + clientIP);
    int loginErrorCount = 0;
    if (bP.get(clientIP) != null) {
      loginErrorCount = ((Integer)bP.get(clientIP)).intValue();
    }
    loginErrorCount++;
    bP.put(clientIP, Integer.valueOf(loginErrorCount));
  }
  
  public void clearMap()
  {
    logger.info("clearBlackList loginErrorCountMap size:" + bP.size());
    bP.clear();
    logger.info("clear blackList oginErrorCountMap size:" + bP.size());
  }
  
  public static void main(String[] args)
  {
    bP.get("1234");
  }
}
